package com.sljy.hzk.ui.detection;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.renderscript.Sampler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sljy.hzk.R;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.DangerDatabaseEntity;
import com.sljy.hzk.entity.DetectionDangerEntity;
import com.sljy.hzk.entity.DetectionHistroyEntity;
import com.sljy.hzk.entity.DetectionPartitionEntity;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.CommonResult;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.DetectionService;
import com.sljy.hzk.room.AppDataBase;
import com.sljy.hzk.room.dao.DangerDao;
import com.sljy.hzk.ui.fragment.DetectionFragment;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sljy.hzk.annotation.ActivityInfo.TITLE_TWO_LEVEL;

@ActivityInfo(layout = R.layout.activity_detection_main, isShowActionBar = true,title = "危害因素", rightIcRes = R.drawable.add_common)
public class DetectionMainActivity extends BaseActivity {
    @BindArray(R.array.detection_tab)
    String[] titles;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.tv_nums)
    TextView tvNums;
    private List<Fragment> fragments = new ArrayList<>();
    UserEntity user;
    int size = 0;//未完成数量
    DangerDao dangerDao;
    List<DetectionHistroyEntity> finishData;
    private int[] imgRes = {
            R.drawable.common_select,
            R.drawable.common_select
    };


    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);
        user = UserInfo.getUserInfo();
        dangerDao = AppDataBase.getInstance().getDangerDao();
        HttpHeper.get().create(DetectionService.class)
                .getHistroyInfo(user.getComPId(), user.getPId(),user.getUserId())
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(getThread())
                .subscribe(new BaseCallBack<List<DetectionHistroyEntity>>(this) {
                    @Override
                    public void onCallBackSuccess(List<DetectionHistroyEntity> data) {
                        Log.i(TAG,"上传失败");
                        finishData = data;
                        setNums(data.size());
                        initFragment();
                    }

                    @Override
                    public void onFail(String mes) {
                        Log.i(TAG,"上传失败");
                    }
                });

    }

    public List<DetectionHistroyEntity> getFinishData(){
        return finishData;
    }

   // @SuppressLint("SetTextI18n")
   // @Recipient(tag = "DetectionDataHaveChange")
    public void setNums(int size) {
        size = AppDataBase.getInstance().getDangerDao().get(false).size()+size;
        tvNums.setText("合计" + size + "条");
    }

    @OnClick(R.id.tv_up)
    void up() {
        List<DangerDatabaseEntity>  dangerCacheList = dangerDao.getById(String.valueOf(user.getUserId()));
        if(dangerCacheList == null ){
            showToast("暂无待上传数据");
            return;
        }
        if (dangerCacheList.size() == 0) {
            showToast("暂无待上传数据");
            return;
        }
        MaterialDialog progressDialog =  new MaterialDialog.Builder(this)
                .content("上传中请稍等")
                .progress(true, 0).build();
        user = UserInfo.getUserInfo();
        DetectionService service = HttpHeper.get().create(DetectionService.class);
        Observable.fromIterable(dangerCacheList)
                .subscribeOn(Schedulers.newThread())
                .map(item -> {
                    Response<CommonResult<Object>> response =  service.submitSynchro(user.getUserId(), item.getRecordName(), item.getpId(), user.getComPId(), item.getDataJson()).execute();
                    if (response.isSuccessful() && response.body().isSuccessful()){
                       // item.setFinsh(true);
                        dangerDao.delete(item);
                    }
                    return item;
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe((disposable) -> progressDialog.show())
                .doOnComplete(() -> {
                    showToast("上传成功");
                    RxEventProcessor.get().post("DetectionDataHaveChange");
                    progressDialog.dismiss();
                }).subscribe();
    }

    void initFragment() {
        tablayout.setTabMode(TabLayout.MODE_FIXED);
        fragments.add(DetectionFragment.get(DetectionFragment.TYPE_FINSH));
        fragments.add(DetectionFragment.get(DetectionFragment.TYPE_UNFINSH));
        viewpager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
//                Drawable image = ContextCompat.getDrawable( DetectionMainActivity.this,imgRes[position]);
//                image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
//                SpannableString sb = new SpannableString(" ");
//                ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
//                sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                return sb;
            }
        });
        tablayout.setupWithViewPager(viewpager);
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewpager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 添加
     */
    @Override
    protected void onRightClick() {
       startActivity(AddDetectionActivity.class);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);
    }
}
